package com.wing.device.controller.admin;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.annotation.RequestObjectFieldIgnore;
import com.wing.common.enums.MaintenanceEnum;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.device.model.entity.Maintenance;
import com.wing.device.model.entity.MaintenanceExecute;
import com.wing.device.model.request.MaintenanceExeDetailForm;
import com.wing.device.model.response.MaintenanExecuteDetailVo;
import com.wing.device.model.response.MaintenanceExecuteVo;
import com.wing.device.model.response.MaintenanceVo;
import com.wing.device.service.DeviceMaintenanceExecuteDetailService;
import com.wing.device.service.DeviceMaintenanceExecuteService;
import com.wing.device.service.DeviceMaintenanceService;
import com.wing.web.db.config.util.DynamicDataSource;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @version 1.1.0
 * @Author hz
 * @Date 2024-08-19 15:13
 **/
@Validated
@Api(value = "Admin-设备维修保养执行管理", tags = "#/device/maintenanceExecute")
@RestController("maintenanceExecuteController")
@RequestMapping("device/admin/maintenanceExecute")
@Slf4j
public class DeviceMaintenanceExecuteController {

    @Resource
    private DeviceMaintenanceExecuteService deviceMaintenanceExecuteService;

    @Resource
    private DeviceMaintenanceService deviceMaintenanceService;

    @Resource
    private DeviceMaintenanceExecuteDetailService deviceMaintenanceExecuteDetailService;


    @ApiOperation(value = "查询设备维修保养认领记录列表", notes = "搜索")
    @GetMapping("/list")
    public PageResult<MaintenanceExecuteVo> list(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer limit,
            @RequestParam(defaultValue = "create_time") String sort,
            @RequestParam(defaultValue = "asc") String order,
            String status,
            String taskNo,
            String departmentSearchExecuteId,
            String postIdSearchClaim,
            String createName,
            String deviceNo,
            String claimName,
            String postId
            ){
        Page<MaintenanceExecuteVo> pg = new Page<>(page, limit);
        Map map = new HashMap();
        map.put("status", status);
        map.put("taskNo", taskNo);
        map.put("departmentSearchExecuteId", departmentSearchExecuteId);
        map.put("postIdSearchClaim", postIdSearchClaim);
        //录入人
        map.put("createName", createName);
        map.put("deviceNo", deviceNo);
        map.put("postId", postId);
        //认领人
        map.put("claimName", claimName);
        String databaseUser = DynamicDataSource.USER_PREFIX;
        if (StringUtils.isNotBlank(DynamicDataSource.name.get())) {
            databaseUser = databaseUser + "-" + DynamicDataSource.name.get();
        }
        map.put("databaseUser", databaseUser);
        IPage<MaintenanceExecuteVo> list = deviceMaintenanceExecuteService.pageList4app(pg, map);
        List<MaintenanceExecuteVo> records = list.getRecords();
        records.stream().forEach(info->{
            info.setStatusName(MaintenanceEnum.StatusEnum.getNameByCode(info.getStatus()));
            info.setTaskTypeName(MaintenanceEnum.TaskEmum.getNameByCode(info.getTaskType()));
        });
        //关联相关业务属性
       return new PageResult<>(list.getRecords(), list.getTotal());
    }

    /**
     * 添加任务执行记录
     * @param form 提交表单信息
     * @return
     */
    @ApiOperation(value = "添加维保任务执行记录", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/add")
    public JsonResult add(@RequestBody MaintenanceExeDetailForm form) {
        try {
            int result = 0 ;
            //1.添加 临时任务
            if (StringUtils.isNotEmpty(form.getTaskType())
                    && form.getTaskType().equals(MaintenanceEnum.TaskEmum.LSRW.getCode())) {
                result = deviceMaintenanceExecuteService.addTemporaryTaskBy(form);
            }
            //添加认领任务
            else if(StringUtils.isNotEmpty(form.getTaskType())
                    && form.getTaskType().equals(MaintenanceEnum.TaskEmum.RLRW.getCode())){
                result = deviceMaintenanceExecuteService.addGettingTaskBy(form);
            }
            if (result > 0) {
                return JsonResult.success("添加成功！");
            }else{
                return JsonResult.success("添加失败！");
            }
        }catch (Exception e){
            return JsonResult.fail(e.getMessage());
        }
    }




    /**
     * 获取维保任务详情信息
     * @param id
     * @return
     */
    @ApiOperation(value = "获取认领任务详情信息", notes = "认领详情信息")
    @GetMapping("/getMaintenanceClaimById")
    public JsonResult getMaintenanceClaimById(Long id) {
        try {
            Maintenance type = deviceMaintenanceService.getById(id);
            if (ObjectUtil.isEmpty(type)){
                return JsonResult.fail("无效id！");
            }
            String databaseUser = DynamicDataSource.USER_PREFIX;
            if (StringUtils.isNotBlank(DynamicDataSource.name.get())) {
                databaseUser = databaseUser + "-" + DynamicDataSource.name.get();
            }

            MaintenanceVo maintenanceVo = deviceMaintenanceService.getMaintenanceBy(id, databaseUser);
            maintenanceVo.setStatusName(MaintenanceEnum.StatusEnum.getNameByCode(maintenanceVo.getStatus()));
            maintenanceVo.setTaskTypeName(MaintenanceEnum.TaskEmum.getNameByCode(maintenanceVo.getTaskType()));
            maintenanceVo.setExamineTypeName(MaintenanceEnum.AduitEnum.getNameByCode(maintenanceVo.getExamineType()));

            //先创建一个假的 到时候在数据了 换成查询数据
            MaintenanceExecute execute = deviceMaintenanceExecuteService.query().eq("task_id", id).one();
            if (ObjectUtil.isNotEmpty(execute)) {
                //获取物料明细
                List<MaintenanExecuteDetailVo> maintenanExecuteDetailVos = deviceMaintenanceExecuteDetailService.selectListByExecuteId(execute.getId());

                BigDecimal totalPic = maintenanExecuteDetailVos.stream().map(info -> {
                    //相乘保留两位小数
                    return info.getOnePrice().setScale(2, RoundingMode.HALF_UP);
                }).reduce(BigDecimal.ZERO, BigDecimal::add);
                maintenanceVo.setTotalMoney(totalPic);
                maintenanceVo.setMaintenanExecuteDetailVos(maintenanExecuteDetailVos);
            }
            return JsonResult.success(maintenanceVo);
        } catch (Exception e) {
            return JsonResult.fail("详情信息有误:" + e.getMessage());
        }
    }
}
